package com.chenqi.controller;

import com.chenqi.authentication.code.KaptchaImageCodeConfig;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @description: 自定义登陆控制器
 * @program: ardai-securtiy-parent
 * @author: ChenQi
 * @create: 2021-03-2021/3/17-09-32
 */
@Slf4j
@Controller
public class CustomLoginController {

    public static final String SESSION_KEY = "Kaptcha";

    @Autowired
    private DefaultKaptcha  defaultKaptcha;

    @RequestMapping("/login/page")
    public String toLogin() {
        return "login";
    }

    @RequestMapping("/code/image")
    public void imageCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //1.获取验证码字符串
        String code = defaultKaptcha.createText();
        log.info("生成的验证码为:{}",code);
        //2.将验证码存入session当中
        request.getSession().setAttribute(SESSION_KEY,code);
        //3.获取验证码图片
        BufferedImage image = defaultKaptcha.createImage(code);
        ServletOutputStream outputStream = response.getOutputStream();
        //4.把验证码图片写出去
        ImageIO.write(image, "jpg", outputStream);
    }
}
